package com.rsscollector.controller.taglibs.app;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;

public class GetPageURLTag extends SimpleTagSupport {
    @Override
	public void doTag() throws JspException, IOException {
        JspWriter writer = this.getJspContext().getOut();
        try {
            HttpServletRequest request = (HttpServletRequest) ((PageContext) this.getJspContext()).getRequest();
            writer.print(getUrl(request));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String getUrl(HttpServletRequest req) {
        String scheme = req.getScheme();             // http
        String serverName = req.getServerName();     // hostname.com
        int serverPort = req.getServerPort();        // 80
        String contextPath = req.getContextPath();   // /mywebapp
        String servletPath = req.getServletPath();   // /servlet/MyServlet
        String pathInfo = req.getPathInfo();         // /a/b;c=123
        String queryString = req.getQueryString();          // d=789

        // Reconstruct original requesting URL
        String url = scheme + "://" + serverName;
        if (!(scheme.equals("http") && serverPort == 80 || scheme.equals("https") && serverPort == 443)) {
            url += ":" + serverPort;
        }
        url += contextPath;
        if (url.endsWith("/")) url = url.substring(0, url.length() - 1);
        url += servletPath;
        if (pathInfo != null) {
            url += pathInfo;
        }
        if (queryString != null) {
            url += "?" + queryString;
        }
        return url;
    }

}
